package com.uatair.common.tcp.client;

import com.uatair.common.tcp.util.TianjinTcp;
import com.uatair.common.tcp.util.TianjinTcp.Message;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.UUID;

public class TcpTianJinClient {
    private static final Logger logger = LoggerFactory.getLogger(TcpTianJinClient.class);

    private static final String SERVER_IP = "123.59.7.55";
    private static final int SERVER_PORT = 29325;
    private static final String key = "914403003116581250";
    private static final String secret = "2b095e982563f55148219948689a1da6";

    private static Channel channel;
    private static EventLoopGroup workerGroup;

    public void connect() throws InterruptedException {
        workerGroup = new NioEventLoopGroup();

        try {
            Bootstrap b = new Bootstrap();
            b.group(workerGroup)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();

                            // 处理粘包/拆包
//                            pipeline.addLast(new LengthFieldBasedFrameDecoder(1048576, 0, 4, 0, 4));
//                            pipeline.addLast(new SimpleFrameDecoder());  // 帧解码
//                            pipeline.addLast(new LengthFieldPrepender(4)) // 帧编码
//                                    .addLast(new ProtobufDecoder(Message.getDefaultInstance())) // Protobuf解码
//                                    .addLast(new ProtobufEncoder());     // Protobuf编码

                            // 业务处理器
                            pipeline.addLast(new UavClientHandler());
                        }
                    });

            // 连接服务器
            ChannelFuture f = b.connect(SERVER_IP, SERVER_PORT).sync();
            channel = f.channel();
            logger.info("成功连接到服务器 {}:{}", SERVER_IP, SERVER_PORT);

            // 发送登录信息
            sendLoginInfo();

            // 等待连接关闭
//            f.channel().closeFuture().sync();
        } finally {
            workerGroup.shutdownGracefully();
        }
    }

    public void sendMessage(Message message) {
        channel.writeAndFlush(message);
        logger.info("已发送信息：{}",message);
    }

    private void sendLoginInfo() {
        // 这里应该使用实际的key和secret，从开发者平台获取
        TianjinTcp.LoginInfo loginInfo = TianjinTcp.LoginInfo.newBuilder()
                .setUserName(key)
                .setPassword(secret)
                .build();

        Message message = Message.newBuilder()
                .setDataType(Message.DataType.LOGININFOTYPE)
                .setVersion(Message.ProtocolVersion.V1_0_1)
                .setLoginInfo(loginInfo)
                .build();
        sendMessage(message);
    }

    public void sendFlightRecord() {
        // 构建飞行记录
        TianjinTcp.FlightRecord flightRecord = buildFlightRecord();

        Message message = Message.newBuilder()
                .setDataType(Message.DataType.FLIGHTRECORDTYPE)
                .setVersion(Message.ProtocolVersion.V1_0_1)
                .setFlightRecord(flightRecord)
                .build();

        sendMessage(message);
    }

    public void sendFlightRecordDetail() {
        // 构建飞行记录明细
        TianjinTcp.FlightRecordDetail flightRecordDetail = buildFlightRecordDetail();

        Message message = Message.newBuilder()
                .setDataType(Message.DataType.FLIGHTRECORDDETAILTYPE)
                .setVersion(Message.ProtocolVersion.V1_0_1)
                .setFlightRecordDetail(flightRecordDetail)
                .build();

        sendMessage(message);
    }

    public void sendUavInfo() {
        // 构建无人机信息
        TianjinTcp.UavInfo uavInfo = buildUavInfo();

        Message message = Message.newBuilder()
                .setDataType(Message.DataType.UAVINFOTYPE)
                .setVersion(Message.ProtocolVersion.V1_0_1)
                .setUavInfo(uavInfo)
                .build();

        sendMessage(message);
    }

    private TianjinTcp.FlightRecord buildFlightRecord() {
        // 这里构建一个示例飞行记录，实际应用中应根据无人机数据填充
        String uuid = UUID.randomUUID().toString();

        TianjinTcp.Position position = TianjinTcp.Position.newBuilder()
                .setLongitude(116.404)
                .setLatitude(39.915)
                .build();

        TianjinTcp.TimeRange timeRange = TianjinTcp.TimeRange.newBuilder()
                .setStart(System.currentTimeMillis() - 3600000)
                .setEnd(System.currentTimeMillis())
                .build();

        TianjinTcp.SimplifyPoint simplifyPoint = TianjinTcp.SimplifyPoint.newBuilder()
                .setPosition(position)
                .setIsSpray(true)
                .setIsSow(false)
                .setWorkMode(4) // WP模式
                .build();

        return TianjinTcp.FlightRecord.newBuilder()
                .setUuid(uuid)
                .addSimplifyPoints(simplifyPoint)
                .setCollectTime(System.currentTimeMillis())
                .setWorkTime(3600000) // 1小时
                .setStartEnd(timeRange)
                .setCreatedAt(System.currentTimeMillis())
                .setLocation("广东省深圳市")
                .setPosition(position)
                .setWorkArea(50.5f) // 50.5亩
                .setUsageType(0) // 喷洒
                .setSprayUsage(5000) // 5000ml
                .setDroneType("Q100")
                .setHardwareId("612737023107")
                .setBodyCode("WLAM0GC03493CM")
                .setBatterySn("UA3WWDZ-U50C4C0F31")
                .build();
    }

    private TianjinTcp.FlightRecordDetail buildFlightRecordDetail() {
        String uuid = UUID.randomUUID().toString();

        TianjinTcp.TimeRange timeRange = TianjinTcp.TimeRange.newBuilder()
                .setStart(System.currentTimeMillis() - 3600000)
                .setEnd(System.currentTimeMillis())
                .build();

        TianjinTcp.Position position = TianjinTcp.Position.newBuilder()
                .setLongitude(116.404)
                .setLatitude(39.915)
                .build();

        TianjinTcp.Velocity velocity = TianjinTcp.Velocity.newBuilder()
                .setX(5.0f)
                .setY(5.0f)
                .setZ(0.0f)
                .build();

        TianjinTcp.SprayInfo sprayInfo = TianjinTcp.SprayInfo.newBuilder()
                .setSprayType(1) // 喷洒中
                .setFlowSpeed(500) // 500mL/min
                .setResidualPesticide(2000) // 2000ml剩余
                .build();

        TianjinTcp.FlightData flightData = TianjinTcp.FlightData.newBuilder()
                .setCollectTime(System.currentTimeMillis())
                .setPosition(position)
                .setVelocity(velocity)
                .setHeight(5.0f) // 5米高度
                .setWorkMode(4) // WP模式
                .setSprayWidth(6.0f) // 6米喷幅
                .setSprayInfo(sprayInfo)
                .build();

        return TianjinTcp.FlightRecordDetail.newBuilder()
                .setCount(1)
                .setUuid(uuid)
                .setHardwareId("612737023107")
                .setBodyCode("WLAM0GC03493CM")
                .setStartEnd(timeRange)
                .addData(flightData)
                .build();
    }

    private TianjinTcp.UavInfo buildUavInfo() {
        return TianjinTcp.UavInfo.newBuilder()
                .setHardwareId("612737023107")
                .setBodyCode("WLAM0GC03493CM")
                .setUavMode("LHFJ Q100")
                .setBdIdentification("Y") // 硬件北斗
                .setCompanyCode("859 ")
                .build();
    }

    public void disconnect() {
        if (channel != null) {
            channel.close();
        }
        if (workerGroup != null) {
            workerGroup.shutdownGracefully();
        }
        logger.info("已断开与服务器的连接");
    }

    public static void main(String[] args) throws InterruptedException {
        TcpTianJinClient client = new TcpTianJinClient();
        try {
            client.connect();

            // 连接成功后发送各种信息
            Thread.sleep(1000); // 等待登录响应

            client.sendUavInfo();
            client.sendFlightRecord();
            client.sendFlightRecordDetail();

            // 保持连接一段时间
            Thread.sleep(5000);
        } finally {
            client.disconnect();
        }
    }
}

class UavClientHandler extends ChannelInboundHandlerAdapter {
    private static final Logger logger = LoggerFactory.getLogger(UavClientHandler.class);

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg instanceof Message) {
            Message message = (Message) msg;

            switch (message.getDataType()) {
                case LOGINRESPONSETYPE:
                    handleLoginResponse(message.getLoginResponse());
                    break;
                // 其他消息类型的处理可以在这里添加
                default:
                    logger.info("收到未处理的消息类型: {}", message.getDataType());
            }
        }
    }

    private void handleLoginResponse(TianjinTcp.LoginResponse loginResponse) {
        if (loginResponse.getCode() == 0) {
            logger.info("登录成功: {}", loginResponse.getMsg());
        } else {
            logger.error("登录失败: {}", loginResponse.getMsg());
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        logger.error("通信异常", cause);
        ctx.close();
    }
}
